﻿using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Xml.Linq;

namespace SlamCms.Configuration
{
	public class EnvironmentConfiguration : Configuration, IConfigurationSettings
	{	
		private EnvironmentConfigurationConnectionStringDictionary _connectionStrings;
		private ConfigurationSettingDictionary _settings;
		private ConfigurationApplicationDictionary _applications;
		private ConfigurationApplication _defaultApplication;
		private EnvironmentConfigurationConnectionString _defaultConnectionString;

		public EnvironmentConfiguration()
		{
			string environmentConfigPath = Path.Combine(ConfigurationManager.ConfigurationFolderPath, "Environment.config");
			if (!File.Exists(environmentConfigPath))
			{
				throw new FileNotFoundException("Environment.config not found. SLAM CMS Configuration expects the Environment.config for this application to exist at " + environmentConfigPath);
			}
			
			Load(XDocument.Load(environmentConfigPath));

			ConfigurationHelpers.LoadProperties(this);
		}

		public ConfigurationApplicationDictionary Applications
		{
			get
			{
				return _applications;
			}
		}

		public ConfigurationApplication DefaultApplication
		{
			get
			{
				return _defaultApplication;
			}
		}

		public EnvironmentConfigurationConnectionStringDictionary ConnectionStrings
		{
			get
			{
				return _connectionStrings;
			}
		}

		public EnvironmentConfigurationConnectionString DefaultConnectionString
		{
			get
			{
				return _defaultConnectionString;
			}
		}

		public ConfigurationSettingDictionary Settings
		{
			get
			{	
				return _settings;
			}
		}

		protected override void Load(XDocument configurationXml)
		{
			base.Load(configurationXml);
			_applications = new ConfigurationApplicationDictionary(this);
			_connectionStrings = new EnvironmentConfigurationConnectionStringDictionary(this);
			_settings = new ConfigurationSettingDictionary(this);

			if (_applications.Any())
				_defaultApplication = _applications.FirstOrDefault().Value;

			if (_connectionStrings.Any())
				_defaultConnectionString = _connectionStrings.FirstOrDefault().Value;
		}

		
	}
}
